<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回顶部功能</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #box {
            height: 2000px;
        }
        #top {
            width: 30px;
            height: 30px;
            position: fixed;
            right: 0;
            bottom: 100px;
            cursor: pointer;
            border: 1px solid red;
            /* display: none; */
        }
    </style>
</head>

<body>
    <div id="box">
        <img id="top" src="https://res.dcdev.net/dcdev/v1.0.3/assets/images/close.svg" alt="返回顶部图标">
    </div>
    <script>
        var top = document.getElementById('top');
        function scrollToTop(t) {
            var x = 0;
            // 获取页面的 scroll_top 值等于当前页面的 scrollTop 值
            var scroll_top = document.body.scrollTop || document.documentElement.scrollTop;
            var time = setInterval(function () {
                x += scroll_top * 30 / t;  // 到达顶部的总时间
                if (x > scroll_top) {
                    clearInterval(time);  // 清除时间
                    document.body.scrollTop = 0;
                    document.documentElement.scrollTop = 0;
                } else {
                    document.body.scrollTop = scroll_top - x;
                    document.documentElement.scrollTop = scroll_top - x;
                }
            }, 30)
        }
        // 点击时执行函数 scrollToTop（）来返回顶部  
        top.onclick = function () {
            scrollToTop(600);  // 返回到顶部所需要的时间
        }
    </script>
</body>

</html>
